//
//  USMomentsAddController.m
//  us
//
//  Created by karry on 2025/6/2.
//

#import "USMomentsAddController.h"
#import "USMomentsPhotoCell.h"
#import "USMediaPickerManager.h"
#import "USMediaUploadManager.h"
#import "IQKeyboardManager.h"
#import <UITextView+Placeholder/UITextView+Placeholder.h>

@interface USMomentsAddController ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITextView *contentTextView;
@property (nonatomic, strong) UICollectionView *photoCollectionView;
@property (nonatomic, strong) UILabel *countLab;

@property (nonatomic ,strong) NSMutableArray <USPhotoModel *>*photoList;
@property (nonatomic ,strong) NSMutableArray <USMediaResult *>*mediaList;
@property (nonatomic,strong) USShareSpaceModel *spaceModel;

@end

@implementation USMomentsAddController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    
    if (!self.momentModel) {
        self.momentModel = [USMomentsModel new];
    }else{
        [self loadData];
    }
    
    [self getShareSpace];
}
 
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 10;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 50;
    IQKeyboardManager.sharedManager.enableAutoToolbar = YES;
 
    if (!self.isEdit) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.contentTextView becomeFirstResponder];
        });
    }
}


- (void)setupView {
    
    NSString *dayStr = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    
    self.navigationItem.title = dayStr;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_close"] style:UIBarButtonItemStylePlain target:self action:@selector(closeAction)];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_gouzi"] style:UIBarButtonItemStylePlain target:self action:@selector(doneAction:)];

    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.alwaysBounceHorizontal = NO;
    self.scrollView.bounces = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag; // 滚动时自动收起键盘（可选）
    [self.view addSubview:self.scrollView];

    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    // 内容容器
    UIView *contentView = [[UIView alloc] init];
    [self.scrollView addSubview:contentView];

    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView); // ✅ 禁止横向滚动关键
    }];
    
    self.contentTextView = [[UITextView alloc]init];
    self.contentTextView.backgroundColor = UIColor.clearColor;
    self.contentTextView.textColor = UIColor.labelColor;
    [self.contentTextView setFont:[UIFont systemFontOfSize:16]];
    self.contentTextView.delegate = self;
    self.contentTextView.placeholder = @"写点什么吧";
    [contentView addSubview:self.contentTextView];
    self.contentTextView.scrollEnabled = NO;
    [self.contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(28);
        make.left.mas_equalTo(22);
        make.right.mas_equalTo(-22);
        make.height.mas_equalTo(100);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat margin = 10;
    CGFloat w = 92;
    layout.itemSize = CGSizeMake(w, w);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumLineSpacing = margin;
    layout.minimumInteritemSpacing = margin;
    self.photoCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.photoCollectionView.dataSource = self;
    self.photoCollectionView.delegate = self;
    self.photoCollectionView.backgroundColor = UIColor.clearColor;
    
    [self.photoCollectionView registerClass:[USMomentsPhotoCell class] forCellWithReuseIdentifier:@"USMomentsPhotoCell"];
    [contentView addSubview:self.photoCollectionView];
    [self.photoCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentTextView.mas_bottom).offset(8);
        make.left.mas_equalTo(24);
        make.height.mas_equalTo(92);
        make.width.mas_equalTo(92 * 3 + 20);
    }];
    
    self.countLab = [[UILabel alloc]init];
    [contentView addSubview:self.countLab];
    self.countLab.font = [UIFont systemFontOfSize:12];
    self.countLab.text = @"0/1000";
    self.countLab.textColor = [UIColor.titleColor jk_lightenColor:0.6];
    self.countLab.textAlignment = NSTextAlignmentRight;
    [self.countLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-22);
        make.top.equalTo(self.photoCollectionView.mas_bottom).offset(24);
        make.height.mas_equalTo(22);
    }];
    
    UIView *line = [[UIView alloc]init];
    [contentView addSubview:line];
    line.backgroundColor = UIColor.mi_3_color;
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.countLab.mas_bottom).offset(10);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(1);
        make.bottom.mas_equalTo(0);
    }];
    
 
    @weakify(self);
 
    [[self.contentTextView.rac_textSignal takeUntil:self.rac_willDeallocSignal]
     subscribeNext:^(NSString * _Nullable text) {
        @strongify(self);

        // 拼音输入中不处理样式更新
        UITextRange *markedRange = [self.contentTextView markedTextRange];
        UITextPosition *pos = [self.contentTextView positionFromPosition:markedRange.start offset:0];
        if (pos) return;

        // ✅ 超限截断处理
        if (text.length > 1000) {
            NSString *trimmedText = [text substringToIndex:1000];
            
            [self setContentAttributeText:trimmedText];
        } else {
            [self setContentAttributeText:text];
        }
        
    }];

     
    RACSignal *textSignal = [self.contentTextView.rac_textSignal map:^id _Nullable(NSString * _Nullable text) {
        return @(text.length > 0);
    }];

    RACSignal *photoArraySignal = [RACObserve(self, photoList) map:^id _Nullable(NSArray *arr) {
        return @(arr.count > 0);
    }];
    
    RACSignal *imageArraySignal = [RACObserve(self, mediaList) map:^id _Nullable(NSArray *arr) {
        return @(arr.count > 0);
    }];

    RACSignal *enableSignal = [RACSignal combineLatest:@[textSignal,photoArraySignal, imageArraySignal]
                                                 reduce:^id(NSNumber *hasText, NSNumber *hasPhoto, NSNumber *hasImage){
        return @([hasText boolValue] || [hasPhoto boolValue] || [hasImage boolValue]);
    }];

    RAC(self.navigationItem.rightBarButtonItem, enabled) = enableSignal;
    
}
- (void)setContentAttributeText:(NSString *)text {
    // 更新字数
    NSUInteger currentLength = text.length;
    self.countLab.text = [NSString stringWithFormat:@"%lu/1000", (unsigned long)currentLength];

 
    self.contentTextView.text = text;
    // 自适应高度
    CGSize size = [self.contentTextView sizeThatFits:CGSizeMake(self.view.jk_width - 44, CGFLOAT_MAX)];
    [self.contentTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(MAX(100, size.height));
    }];
}
 
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // 处理拼音输入，不限制
    UITextRange *markedRange = [textView markedTextRange];
    if (markedRange) {
        UITextPosition *pos = [textView positionFromPosition:markedRange.start offset:0];
        if (pos) {
            return YES;
        }
    }

    // 处理粘贴场景的长度限制
    NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if (newText.length > 1000) {
        // 超限则截断文本
        NSInteger allowedLength = 1000 - (textView.text.length - range.length);
        if (allowedLength > 0 && allowedLength < text.length) {
            NSString *allowedText = [text substringToIndex:allowedLength];
            
            // 手动插入截断后的字符串（此时不返回 YES，而是手动替换）
            NSMutableString *mutableText = [textView.text mutableCopy];
            [mutableText replaceCharactersInRange:range withString:allowedText];
            
            textView.text = mutableText;
            
            // 触发文本更新逻辑（可选，如果你没有绑定）
            [self setContentAttributeText:textView.text];
            
            self.navigationItem.rightBarButtonItem.enabled = YES;//解决复制内容超过1000个字，截断粘贴不触发rac问题

        }

        return NO; // 拦截原始粘贴内容
    }

    return YES;
}


- (NSMutableArray <USPhotoModel *>*)photoList {
    if (_photoList == nil) {
        _photoList = [NSMutableArray array];
    }
    return _photoList;
}
- (NSMutableArray <USMediaResult *>*)mediaList {
    if (_mediaList == nil) {
        _mediaList = [NSMutableArray array];
    }
    return _mediaList;
}
- (void)loadData {
    [self setContentAttributeText:self.momentModel.moodDiaryDto.diaryContent];
    
    NSMutableArray *newArray = [self.photoList mutableCopy];
    [newArray addObjectsFromArray:self.momentModel.photoList];
    self.photoList = newArray;
    
    [self reloadPhotoData];
    
}

- (void)getShareSpace{

    [[EMNetWork shareManager] em_post:API_SharedSpaceInfo
                               params:@{}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
 
        self.spaceModel = [USShareSpaceModel mj_objectWithKeyValues:api.data[@"sharedSpace"]];
        
 
    } fail:^{
        
        
    }];
    
    
}

- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.doneItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

- (void)closeAction {
    [self.view endEditing:YES];
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"是否仍要退出？" detailTitle:@"当前内容尚未发布。退出后，本次记录将被丢弃且无法恢复。" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = UIColor.us_redColor;
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    };
    
    [alert showInView:self.view];

}

- (void)doneAction:(id)sender{
    [super doneAction:sender];
    [USFeedbackTool impactSoft];
    
    [self.view endEditing:YES];
    
    if (self.mediaList.count > 0 && self.spaceModel.albumStorageSize >= 500) {
        
        MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"相册存储空间已达上限\n塞不进去啦~" detailTitle:nil contentView:nil leftButtonImageName:@" " rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
        
        [alert showInView:self.view];
        return;
    }
     
    
    [self startUpload];
    
    if (self.mediaList.count > 0) {
        [EMHudManager show:@"上传中..."];
        
         NSString * albumFirstDirectory = [NSString stringWithFormat:@"%@/%@",[USUser user].sharedSpaceId,NSUUID.UUID.UUIDString];
        [USMediaUploadManager uploadImages:self.mediaList albumFirstDirectory:albumFirstDirectory albumSecondDirectory:@"video" progress:^(NSInteger current, NSInteger total) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (total == 1) {
                    // 单个文件上传进度
                    [EMHudManager showProgress: current / 100.0];
                    [EMHudManager show:[NSString stringWithFormat:@"上传中 %li%%", current]];
                } else {
                    // 多个文件上传进度
                    [EMHudManager showProgress: (float)current / (float)total];
                    [EMHudManager show:[NSString stringWithFormat:@"上传中 %ld/%ld", (long)current, (long)total]];
                }
            });
        } success:^(NSArray<USPhotoModel *> * _Nonnull models) {
            [self addMoodDiary:models];
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }else{
        [self addMoodDiary:nil];
    }
    
}

- (void)addMoodDiary:(NSArray <USPhotoModel *>*)photos{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    
    NSMutableDictionary *moodDiaryDto = [NSMutableDictionary dictionary];
    moodDiaryDto[@"diaryContent"] = self.contentTextView.text?:@"";

    NSString *path = MoodDiaryAdd;
    if (self.isEdit) {
        path = MoodDiaryEdit;
        moodDiaryDto[@"moodDiaryId"] = self.momentModel.moodDiaryDto.moodDiaryId?:@"";
        
    }
    
    params[@"moodDiaryDto"] = moodDiaryDto;

    
    NSMutableArray *list = [NSMutableArray array];
    
    NSMutableArray *photoArr = [NSMutableArray array];
    [photoArr addObjectsFromArray:self.photoList];
    [photoArr addObjectsFromArray:photos];
 
    for (USPhotoModel *model in photoArr) {
        [list addObject:@{
            @"cosUrl":model.cosUrl?:@"",
            @"type":@(model.type),
            @"photoFirstDirectory" :model.photoFirstDirectory?:@"",
            @"photoSecondDirectory":model.photoSecondDirectory?:@"",
            @"recordDate": @(model.recordDate),
            @"fileName":model.fileName?:@"",
            @"liveMovUrl":model.liveMovUrl?:@"",
            @"liveMoveFileName":model.liveMoveFileName?:@"",
            @"size":@(model.size),
            @"liveMovSize":@(model.liveMovSize)
        }];
    }

    params[@"photoList"] = list;

    [[EMNetWork shareManager] em_post:path
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {

        [self endUpLoad];
        if (!api.success) {
            return;
        }
        
        if (self.isEdit) {
            self.momentModel.moodDiaryDto.diaryContent = self.contentTextView.text?:@"";
            self.momentModel.photoList = photoArr;

            if (self.editMomentBlock) {
                self.editMomentBlock(self.momentModel);
            }
        }else{
            USMomentsModel *model = [USMomentsModel mj_objectWithKeyValues:api.data[@"totalMoodDiary"]];
            if (self.addMomentBlock) {
                self.addMomentBlock(model);
            }
            
            [self remindActionWithModel:model];
        }
        [USFeedbackTool notifySuccess];

        [self dismissViewControllerAnimated:YES completion:nil];

    } fail:^{
        
        [self endUpLoad];

    }];
    
}

#pragma mark - 提醒Ta
- (void)remindActionWithModel:(USMomentsModel *)model {
 
    NSString *action_title = [NSString stringWithFormat:@"%@发布了一篇日记",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":model.moodDiaryDto.moodDiaryId?:@"",
                          @"action_title":action_title,
                          @"action_content":@"快来看看吧~"};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_PushMoment andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_PushMoment andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_Moment) forKey:@"type"];
    [param setValue:model.moodDiaryDto.moodDiaryId?:@"" forKey:@"pkId"];
    [param setValue:@"发布了一篇日记" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];
    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}
- (void)reloadPhotoData {
    [self.photoCollectionView reloadData];
    CGFloat height = 0;
    NSInteger totalCount = self.photoList.count + self.mediaList.count;
    if (totalCount < 9) {
        totalCount ++;
    }
    if (totalCount % 3 == 0) {
        height = (92 + 10) * totalCount/3;
    }else{
        height = (92 + 10) * (totalCount/3 + 1);

    }
    [self.photoCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
}

- (void)presentImagePicker{
    [USFeedbackTool impactSoft];
    
    if (self.photoList.count + self.mediaList.count == 9) {
        return;
    }

    @weakify(self)
    [USMediaPickerManager presentPickerFrom:self type:USPickerMediaType_Image limit:9 - self.photoList.count - self.mediaList.count didFinishPicking:^{
    
    } progressHandler:^(NSInteger current, NSInteger total) {
 
        NSLog(@"%ld",current);
        
    } completion:^(NSArray<USMediaResult *> * _Nonnull results) {
        @strongify(self)
                   
        NSMutableArray *newArray = [self.mediaList mutableCopy];
        [newArray addObjectsFromArray:results];
        self.mediaList = newArray; // 🔥 触发 KVO
 
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reloadPhotoData];
        });
        
        
    }];
    
}
#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.photoList.count + self.mediaList.count  < 9 && indexPath.row == self.photoList.count + self.mediaList.count) {
        [self presentImagePicker];
    }else {
        
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
 
}
 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.photoList.count + self.mediaList.count < 9) {
        return self.photoList.count + self.mediaList.count + 1;
    }
    return self.photoList.count + self.mediaList.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.photoList.count + self.mediaList.count < 9 && indexPath.row == self.photoList.count + self.mediaList.count) {

        USMomentsPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USMomentsPhotoCell" forIndexPath:indexPath];
         
        cell.isAdd = YES;
        return cell;
        
    }else{
        USMomentsPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USMomentsPhotoCell" forIndexPath:indexPath];
        
        if (indexPath.row < self.photoList.count) {
            USPhotoModel *photo = self.photoList[indexPath.row];
            cell.photoModel = photo;
        }else{
            USMediaResult *media = self.mediaList[indexPath.row - self.photoList.count];
            cell.media = media;
        }

        
        cell.isAdd = NO;
        @weakify(self)
        cell.deleteBlock = ^{
            @strongify(self)
            
            if (indexPath.row < self.photoList.count) {
                NSMutableArray *newArray = [self.photoList mutableCopy];
                [newArray removeObjectAtIndex:indexPath.row];
                self.photoList = newArray;
            }else{
                NSMutableArray *newArray = [self.mediaList mutableCopy];
                [newArray removeObjectAtIndex:indexPath.row - self.photoList.count];
                self.mediaList = newArray;

            }
          
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadPhotoData];
            });
        };

        return cell;
    }
 
    
}


@end
